package com.tanhua.sso.server.service;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.tanhua.api.*;
import com.tanhua.autoconfig.tmplate.HuanXinTemplate;
import com.tanhua.config.UserHolder;
import com.tanhua.exceptionhander.CustomException;
import com.tanhua.result.Result;
import com.tanhua.sso.pojo.*;
import com.tanhua.sso.vo.NearbyUserVo;
import com.tanhua.sso.vo.TodayBest;
import com.tanhua.sso.vo.UserInfoVo;
import com.tanhua.util.Constants;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.logging.SimpleFormatter;
import java.util.stream.Collectors;

@Service
public class TanhuaService {

    @DubboReference
    private RecommendUserService recommendUserService;

    @DubboReference
    private UserInfoService userInfoService;

    @DubboReference
    private QuestionService questionService;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @Value("${tanhua.default.recommend.users}")
    private String recommendUser;


    @DubboReference
    private UserLikeServiceApi userLikeServiceApi;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    @Autowired
    private MessagesService messagesService;

    @DubboReference
    private UserLocationServiceApi userLocationServiceApi;

    @DubboReference
    private VisitorsServiceApi visitorsServiceApi;

    //查看今日佳人
    public TodayBest selectOne() {
        //获取当前用户id
        Long toUserId = UserHolder.getUserId();
        RecommendUser recommendUser = recommendUserService.selectByid(toUserId);
        //缘分最高的用户id
        Long  userId= recommendUser.getUserId();
        //转换成long类型缘分值
        long score = recommendUser.getScore().longValue();
        //获取userinfo信息
        UserInfo userInfo=userInfoService.selectUser(userId);
        //切割tags
        String[] tags = userInfo.getTags().split(",");
        TodayBest todayBest=new TodayBest();
        BeanUtils.copyProperties(userInfo,todayBest,"tags");
        //身份
        todayBest.setTags(tags);
        //缘分值
        todayBest.setFateValue(score);
        return todayBest;
    }

    //查看所有有缘分的用户
    public List<TodayBest> selectAll() {
        //获取当前用户id
        Long toUserId = UserHolder.getUserId();
        //获取所有有缘分的好友
        List<RecommendUser> list=recommendUserService.selectAll(toUserId);
        //获取所有的id
        List<Long> collect = list.stream().map(RecommendUser::getUserId).collect(Collectors.toList());
        List<TodayBest> bestList=new ArrayList<>();
        for (Long aLong : collect) {

            RecommendUser recommendUser =recommendUserService.selectOne(aLong,toUserId);
            //缘分最高的用户id
            Long  userId= recommendUser.getUserId();
            //转换成long类型缘分值
            long score = recommendUser.getScore().longValue();
            //获取userinfo信息
            UserInfo userInfo=userInfoService.selectUser(userId);
            //切割tags
            String[] tags = userInfo.getTags().split(",");
            TodayBest todayBest=new TodayBest();
            BeanUtils.copyProperties(userInfo,todayBest,"tags");
            //身份
            todayBest.setTags(tags);
            //缘分值
            todayBest.setFateValue(score);
            bestList.add(todayBest);
        }
        return bestList;
    }

    /*佳人信息*/
    public TodayBest personalInfo(Long id) {
        //获取当前用户id
        Long userId = UserHolder.getUserId();

        //如果查不到对象,设置默认缘分值
        Long score=97L;
       //获取缘分信息
        RecommendUser recommendUser=recommendUserService.selectOne(id,userId);
        if (ObjectUtil.isNotEmpty(recommendUser)){
            //转换成long类型缘分值
           score = recommendUser.getScore().longValue();
        }
        //获取userinfo信息
        UserInfo userInfo=userInfoService.selectUser(id);
        //切割tags
        String[] tags = userInfo.getTags().split(",");
        TodayBest todayBest=new TodayBest();
        BeanUtils.copyProperties(userInfo,todayBest,"tags");
        //身份
        todayBest.setTags(tags);
        //缘分值
        todayBest.setFateValue(score);
        //封装对象
        Visitors visitors=new Visitors();
        visitors.setScore(score.doubleValue());
        //被来访的人的id
        visitors.setUserId(id);
        //当前用户id
        visitors.setVisitorUserId(userId);
        visitors.setVisitDate(new SimpleDateFormat("yyyyMMdd").format(new Date()));
        visitors.setDate(System.currentTimeMillis());
        visitors.setFrom("首页");
        //更新来访记录
        visitorsServiceApi.save(visitors);
        return todayBest;
    }


    /*查看陌生人问题*/
    public String getStrangerQuestions(Long userId) {
        Question question=questionService.findById(userId);
        if(ObjectUtil.isNotEmpty(question)){
            String txt = question.getTxt();
            return txt;
        }else {
            return "你喜欢Java编程吗";
        }
    }

    //回复陌生人问题
    public void sendstrangerQuestions(Long userId, String reply) {

        if (StrUtil.isEmpty(reply)){
            throw new CustomException("请输入信息");
        }
        //获取当前用户id
        Long id = UserHolder.getUserId();
        //获取呢陈
        UserInfo userInfo = userInfoService.selectUser(id);
        String nickname = userInfo.getNickname();
        //获取问题
        String txt="你喜欢Java编程吗";
        Question question = questionService.findById(userId);
        if (ObjectUtil.isNotEmpty(question)){
            txt = question.getTxt();
        }
        Map map=new HashMap<>();
        map.put("userId",id);
        map.put("huanXinId", Constants.HX_USER_PREFIX+id);
        map.put("nickname",nickname);
        map.put("strangerQuestion",txt);
        map.put("reply",reply);
        //转换成json
        String message = JSON.toJSONString(map);
        //信息发送给环信服务器
        Boolean aBoolean = huanXinTemplate.sendMsg(Constants.HX_USER_PREFIX + userId, message);
        if (!aBoolean){
            throw new CustomException("系统繁忙,发送失败");
        }
    }


    /*左滑右滑*/
    public List<TodayBest> cards() {
        //获取当前用户id
        Long userId = UserHolder.getUserId();
        //查看推荐用户,去掉喜欢和不喜欢的好友,一次查十条
        List<RecommendUser> list = recommendUserService.selectCards(userId,10);
        //如果没有推荐好友,则系统默认推荐好友
        if (ObjectUtil.isEmpty(list)){
            //初始化
            list=new ArrayList<>();
            String[] userIds = recommendUser.split(",");
            for (String id : userIds) {
                RecommendUser recommendUser = new RecommendUser();
                //默认推荐好友id
                recommendUser.setUserId(Convert.toLong(userId));
                //本人id
                recommendUser.setToUserId(UserHolder.getUserId());
                //随机缘分值
                recommendUser.setScore(RandomUtil.randomDouble(60, 90));
                list.add(recommendUser);
            }
        }
        List<TodayBest> todayBestList=new ArrayList<>();
        for (RecommendUser user : list) {
            TodayBest todayBest=new TodayBest();
            todayBest.setFateValue(user.getScore().longValue());
            UserInfo userInfo = userInfoService.selectUser(user.getUserId());
            todayBest.setTags(userInfo.getTags().split(","));
            todayBest.setAge(userInfo.getAge());
            todayBest.setAvatar(userInfo.getAvatar());
            todayBest.setGender(userInfo.getGender());
            todayBest.setId(userInfo.getId());
            todayBest.setNickname(userInfo.getNickname());
            todayBestList.add(todayBest);
        }
        return todayBestList;
    }


    //喜欢,不喜欢
    public void love(Long likeUserId,boolean flag) {
        //获取当前用户id
        Long userId = UserHolder.getUserId();
        //更新或添加好友关系
        boolean choose=userLikeServiceApi.save(userId,likeUserId,flag);
        if (!choose){
            throw new CustomException("操作失败");
        }
        if (flag) {
            //添加到喜欢的redis里
            redisTemplate.opsForSet().add(Constants.USER_LIKE_KEY+userId,likeUserId.toString());
            //从不喜欢的redis里删除
            redisTemplate.opsForSet().remove(Constants.USER_NOT_LIKE_KEY,likeUserId.toString());
        }else {
            //添加到不喜欢的redis的
            redisTemplate.opsForSet().add(Constants.USER_NOT_LIKE_KEY+UserHolder.getUserId(),likeUserId.toString());
            //从喜欢的redis里删除
            redisTemplate.opsForSet().remove(Constants.USER_LIKE_KEY+UserHolder.getUserId(),likeUserId.toString());
        }
        //查看她是不是也喜欢我,如果喜欢则添加为好友
        boolean like=true;
        boolean apiLike=userLikeServiceApi.isLike(userId,likeUserId,like);
        //两者互相喜欢加好友
        if (apiLike&&flag){
            messagesService.contacts(likeUserId);
            //删除好友
        }else {
            messagesService.deleteFriend(likeUserId);
        }
    }


    /*查询附近*/
    public List<NearbyUserVo> search(String gender, Double distance) {
        //获取当前用户id
        Long userId = UserHolder.getUserId();
        //查询附近是否有用户
        List<Long> listId=userLocationServiceApi.selectUser(userId,distance);
        if (ObjectUtil.isEmpty(listId)){
            throw new CustomException("id不存咋");
        }
        List<NearbyUserVo> nearbyUserVoList=new ArrayList<>();
        //性别查询
        List<UserInfo> userInfoList=userInfoService.selectIds(listId,gender);
        if (ObjectUtil.isEmpty(userInfoList)){
            throw new CustomException("用户不存在");
        }
        for (UserInfo userInfo : userInfoList) {
            NearbyUserVo nearbyUserVo=new NearbyUserVo();
            nearbyUserVo.setUserId(userInfo.getId().intValue());
            nearbyUserVo.setAvatar(userInfo.getAvatar());
            nearbyUserVo.setNickname(userInfo.getNickname());
            nearbyUserVoList.add(nearbyUserVo);
        }
        return nearbyUserVoList;
    }
}

